/**
 * IM
 */
import { sendMessage } from '@/api/imkefu'
// getOfflineMessages
// import { getNewClientHistoricalRecord } from '@/api/imchat'
import { getCustomerInfo, updateCustomer, getHookUserInfo } from '@/api/customer'
// getUserInfo
// import { messageFilter, switchContent } from '@/utils'
import Cookies from 'js-cookie'
import WebIM from '../../utils/WebIM'
// import { MessageBox } from 'mint-ui'
import { watchSession } from '@/utils/watch'
// const now = new Date()
const IM = {
  namespaced: true,
  state: {
    // 当前用户
    user: {
      // id: 10001,
      // name: 'admin',
      // img: '../../static/IM/images/1.jpg'
    },
    // 客服信息
    customerServer: {
      user_id: '100451',
      user_name: '官方医美管家',
      user_photo: 'https://img.rongcat.com/images/2019/08/22/bdWT2tzYu7GZlPh6epfe2WrN4YZmUnPbljket0Fj.jpeg'
    },
    // 离线消息数
    offlineMsgCount: 0,
    // 通知消息数
    noticeMsgCount: 0,
    // 通知id
    noticeId: '204819',
    // 会话列表
    sessions: [],
    // 当前会话人的信息
    currentUser: null,
    // 马甲id
    currentVest: '',
    // 马甲信息
    hook_info: {},
    // 消息拓展信息
    messageExt: null,
    // 当前选中的会话
    currentSessionId: '',
    // 会话筛选key
    filterKey: '',
    // IM窗口是否打开
    isOpenWindow: false,
    // 消息提醒
    msgAlert: {
      show: false,
      title: '',
      type: ''
    }
  },
  getters: {
    // 当前登录用户
    user: ({ user }) => user,

    offlineMsgCount: ({ offlineMsgCount }) => offlineMsgCount,

    noticeMsgCount: ({ noticeMsgCount }) => noticeMsgCount,

    filterKey: ({ filterKey }) => filterKey,

    // 当前会话index
    currentSessionId: ({ currentSessionId }) => currentSessionId,
    // 当前会话信息
    session: ({ sessions, currentSessionId }) => sessions.find(session => session.id === currentSessionId),

    // 过滤后的会话列表
    sessions: ({ sessions, filterKey, noticeId }) => {
      const result = sessions.filter(session => session.user.name.includes(filterKey))
      return result
    },
    // 通知列表
    // notices: ({ notification, noticeId }) => {
    //   const result = notification
    //   result.messages.sort((a, b) => {
    //     return b.date - a.date
    //   })
    //   return result
    // },
    // 会话人的信息
    sessionUser: ({ currentUser }) => {
      return currentUser
    }
  },
  mutations: {
    INIT_DATA(state, user) {
      // console.log('im-initdata-user:::::', user)
      // console.log(state, 'init', user)
      state.user.id = user.user_id ? user.user_id : ''
      state.user.name = user.user_name ? user.user_name : ''
      state.user.img = user.user_photo ? user.user_photo : ''

      state.offlineMsgCount = state.offlineMsgCount ? state.offlineMsgCount : 0
      state.currentSessionId = state.currentSessionId ? state.currentSessionId : ''
      state.filterKey = state.filterKey ? state.filterKey : ''
      state.isOpenWindow = typeof state.isOpenWindow === 'boolean' ? state.isOpenWindow : false
      state.currentVest = state.currentVest ? state.currentVest : ''
      // console.log(state, 'init2', user)

      if (state.user.id) {
        const data = localStorage.getItem('vuex-im-session-' + state.user.id)
        // console.log(data, '存储data')
        if (data) {
          const sessions = JSON.parse(data)
          state.sessions = sessions
          // console.log(sessions, '获取存储消息')、
          state.sessions = sessions.filter(item => {
            if (item.id) {
              return item
            }
          })
        } else {
          localStorage.setItem('vuex-im-session-' + state.user.id, '')
          // console.log('vuex-im-session-' + state.user.id, '获取存储消息12')

          state.sessions = []
          state.currentSessionId = ''
          state.currentUser = {}
        }
      }
    },

    CLEAR_DATA(state) {
      state.user = {}
      state.offlineMsgCount = 0
      state.noticeMsgCount = 0
      state.sessions = []
      state.currentSessionId = ''
      state.filterKey = ''
      state.isOpenWindow = false
      state.currentUser = {}
      state.customerInfo = {}
      state.currentVest = ''
      state.hook_info = {}
      state.notification = {
        id: 1,
        user: {
          name: '通知',
          img: '../../static/IM/images/2.png'
        },
        unReadCount: 0,
        messages: []
      }
    },

    // 获取离线消息数
    GET_OFFLINEMSGCOUNT(state, data) {
      state.offlineMsgCount = data
    },

    // 打开／关闭IM窗口Window
    OC_WINDOW(state, bool) {
      state.isOpenWindow = bool
    },

    // 消息提醒
    MSG_ALERT(state, params) {
      state.msgAlert = {
        show: params.show,
        title: params.title,
        type: params.type
      }
    },

    // 创建会话
    CREATE_SESSION(state, customerChange) {
      // console.log(customerChange, '创建会话', state)
      try {
        state.currentUser = {
          name: customerChange.user_name,
          img: customerChange.user_photo,
          user_id: customerChange.user_id
        }
        // && typeof (state.sessions.find(item => item.id === customer.user_id)) === 'undefined')
        if (state.sessions.length === 0 || (state.sessions.length > 0 && typeof (state.sessions.find(item => item.id === customerChange.user_id + '-' + customerChange.hook_user_id)) === 'undefined')) {
          // console.log('第一次创建')
          state.sessions.unshift({
            id: customerChange.user_id + '-' + customerChange.hook_user_id,
            hook: customerChange.hook,
            hook_user_id: customerChange.hook_user_id,
            user: {
              name: customerChange.user_name,
              img: customerChange.user_photo,
              id: customerChange.user_id
            },
            unReadCount: 0,
            messages: []
          })
          // console.log(state, '第一次创建', state.sessions)
        } else {
          const sessionInd = state.sessions.findIndex(item => item.id === customerChange.user_id + '-' + customerChange.hook_user_id)
          state.sessions[sessionInd].user = {
            name: customerChange.user_name,
            img: customerChange.user_photo,
            user_id: customerChange.user_id
          }
          // console.log('多次创建', state.sessions[sessionInd])
        }
      } catch (e) {
        console.log('CREATE_SESSION:::::', e)
      }
    },

    // 选择会话
    SELECT_SESSION(state, id) {
      try {
        if (id) {
          state.currentSessionId = id
          const session = state.sessions.find(item => {
            return item.id === id
          })
          if (session) {
            // state.currentUser = {
            //   ...session.user
            // }
            state.currentVest = session.hook_user_id
            if (id.indexOf('-') !== -1) {
              state.currentUser = {
                ...session.user,
                user_id: id.split('-')[0]
              }
            }
            // if (session.unReadCount && state.offlineMsgCount > 0 && state.offlineMsgCount >= session.unReadCount) {
            //   state.offlineMsgCount -= session.unReadCount
            // }
            // session.unReadCount = 0
          }
          // console.log(session, 'sesson返回值')
        }
      } catch (e) {
        console.log('SELECT_SESSION:::', e)
      }
    },

    // 发送消息
    SEND_MESSAGE(state, params) {
      console.log(state.sessions, '发送消息')
      // console.log(state.currentSessionId, '发送消息发送消息')
      const session = state.sessions.find(item => item.id === state.currentSessionId)
      if (session) {
        session.messages.push({
          id: params.id,
          type: params.message_type,
          content: params.local_message,
          date: new Date(),
          status: params.status,
          self: true
        })
      } else {
        // this.$toast.error('聊天对话框登录失败，请刷新重试！')
      }

      console.log(session.messages, '发送消息替')
    },

    // 更新消息的mid
    UPDATE_MESSAGE_MID({ sessions, currentSessionId }, message) {
      // console.log(sessions, '更新消息的mid', currentSessionId)
      const session = sessions.find(item => item.id === currentSessionId)
      const { id, mid } = message
      if (session) {
        session.messages.forEach((item) => {
          if (parseInt(item.id) === parseInt(id)) {
            item.id = mid
          }
        })
      }
    },

    // 更新消息状态
    UPDATE_MESSAGE_STATUS({ sessions, currentSessionId }, message) {
      const session = sessions.find(item => item.id === currentSessionId)
      const { id, mid } = message
      if (session) {
        session.messages.forEach((item) => {
          if (parseInt(item.id) === parseInt(mid) || parseInt(item.id) === parseInt(id)) {
            item.status = message.status
          }
        })
      }
    },
    // 接收旧会话的消息
    RECEIVE_OLD_MESSAGE(state, param) {
      // console.log(param, '接收旧会话的消息', state)
      // const stateSessons = param.sessions
      // const smartQuity = param.smart
      try {
        // var message = param.message
        // // var hook = param.hook
        // if (message.ext && message.ext.hook && message.ext.hook.hook_user_id) {
        //   state.currentVest = message.ext.hook.hook_user_id
        // } else {
        //   state.currentVest = message.to
        // }
        // // const from_id = message.ext.hook ? message.from + '-' + message.ext.hook.hook_user_id : message.from + '-' + message.to
        // const session = state.sessions.find(item => item.id === state.currentSessionId)
        // const sessionInd = state.sessions.findIndex(item => item.id === from_id)
        // state.sessions.splice(sessionInd, 1)
        // state.sessions.unshift(session)
        // session.hook = hook
        // session.hook_user_id = state.currentVest

        var message = param.message
        var hook = param.hook

        // console.log(message.ext.hook.hook_user_id, 'message.ext.hook.hook_user_id')
        // var hook = param.hook
        if (message.ext && message.ext.hook) {
          if (typeof (message.ext.hook) === 'string') {
            const hookId = JSON.parse(message.ext.hook)
            state.currentVest = hookId.hook_user_id
          } else {
            state.currentVest = message.ext.hook.hook_user_id
          }
        } else {
          state.currentVest = message.to
        }
        // console.log(new Date(Number(message.time)))
        // const from_id = message.ext.hook ? message.from + '-' + message.ext.hook.hook_user_id : message.from + '-' + param.hook.user_id
        if (typeof (message.ext.hook) === 'string') {
          const hookId = JSON.parse(message.ext.hook)
          var from_id = message.ext.hook ? message.from + '-' + hookId.hook_user_id : message.from + '-' + param.hook.user_id
        } else {
          from_id = message.ext.hook ? message.from + '-' + message.ext.hook.hook_user_id : message.from + '-' + param.hook.user_id
        }

        const session = state.sessions.find(item => {
          return item.id === from_id
        })

        const sessionInd = state.sessions.findIndex(item => item.id === from_id)
        state.sessions.splice(sessionInd, 1)
        state.sessions.unshift(session)
        session.hook = hook
        session.hook_user_id = state.currentVest

        // 防重复
        if (typeof (session.messages.find(item => item.id === message.id)) === 'undefined') {
          if (session.id !== state.noticeId) {
            if (session.id !== state.currentSessionId) {
              session.unReadCount = session.unReadCount ? session.unReadCount : 0
              session.unReadCount++
              state.offlineMsgCount++
            } else {
              if (state.isOpenWindow === false) {
                session.unReadCount = session.unReadCount ? session.unReadCount : 0
                session.unReadCount++
                state.offlineMsgCount++
              }
            }
          }
          if (message.message_type !== 'audio') {
            session.messages.push({
              id: message.id,
              type: message.message_type,
              content: message.data,
              ext: message.ext,
              date: new Date()
            })
          } else {
            session.messages.push({
              id: message.id,
              type: message.message_type,
              content: message.data,
              ext: message.ext,
              message_ext: message.message_ext,
              date: new Date()
            })
          }
        }
      } catch (e) {
        console.log('RECEIVE_OLD_MESSAGE:::::', e)
      }
    },

    // 接收新会话的消息
    RECEIVE_NEW_MESSAGE(state, param) {
      // console.log(state, '接收新会话的消息', param)
      try {
        // var sessions = []
        // sessions = state.sessions
        // var message = param.message
        // var customer = param.customer
        // var hook = param.hook
        // if (message.ext && message.ext.hook && message.ext.hook.hook_user_id) {
        //   state.currentVest = message.ext.hook.hook_user_id
        // } else {
        //   state.currentVest = message.to
        // }
        // console.log('new', sessions)
        // 防止异步等待冲突
        // const from_id = message.ext.hook ? message.from + '-' + message.ext.hook.hook_user_id : message.from + '-' + message.to
        var sessions = []
        sessions = state.sessions
        var message = param.message
        var customer = param.customer
        var hook = param.hook

        if (message.ext && message.ext.hook) {
          if (typeof (message.ext.hook) === 'string') {
            const hookId = JSON.parse(message.ext.hook)
            // var from_id = message.ext.hook ? message.to + '-' + hookId.hook_user_id : ''
            state.currentVest = hookId.hook_user_id
          } else {
            // var from_id = message.ext.hook ? message.to + '-' + message.ext.hook.hook_user_id : ''
            state.currentVest = message.ext.hook.hook_user_id
          }
        } else {
          state.currentVest = message.to
        }
        // console.log(param, '-----接收新会话的消息-----', state, sessions)
        if (typeof (message.ext.hook) === 'string') {
          const hookId = JSON.parse(message.ext.hook)
          var from_id = message.ext.hook ? message.from + '-' + hookId.hook_user_id : message.from + '-' + message.to
        } else {
          from_id = message.ext.hook ? message.from + '-' + message.ext.hook.hook_user_id : message.from + '-' + message.to
        }
        if (sessions && sessions.length > 0 && typeof (sessions.find(item => item.id === state.currentSessionId)) !== 'undefined') {
          const session = sessions.find(item => item.id === state.currentSessionId)
          // console.log('new', message)
          // 防重复
          if (typeof (session.messages.find(item => item.id === message.id)) === 'undefined') {
            if (session.id !== state.currentSessionId) {
              if (session.id !== state.noticeId) {
                session.unReadCount = session.unReadCount ? session.unReadCount : 0
                session.unReadCount++
                state.offlineMsgCount++
              }
            } else {
              if (state.isOpenWindow === false) {
                session.unReadCount = session.unReadCount ? session.unReadCount : 0
                session.unReadCount++
                state.offlineMsgCount++
              }
            }
            if (message.message_type !== 'audio') {
              session.messages.push({
                id: message.id,
                type: message.message_type,
                content: message.data,
                ext: message.ext,
                date: new Date()
              })
              // session.messages.unshift({
              //   id: message.id,
              //   type: message.message_type,
              //   content: message.data,
              //   ext: message.ext,
              //   date: new Date()
              // })
            } else {
              session.messages.push({
                id: message.id,
                type: message.message_type,
                content: message.data,
                ext: message.ext,
                message_ext: message.message_ext,
                date: new Date()
              })
            }
          }
        } else {
          // var newSession = {
          //   id: customer.user_id,
          //   hook_user_id: state.currentVest,
          //   // hook: hook,
          //   user: {
          //     name: customer.user_name,
          //     img: customer.user_photo,
          //     id: customer.user_id
          //   },
          //   unReadCount: 1,
          //   messages: []
          // }
          var newSession = {
            id: from_id,
            hook_user_id: state.currentVest,
            hook: hook,
            user: {
              name: customer.user_name,
              img: customer.user_photo,
              id: customer.user_id
            },
            unReadCount: 1,
            messages: []
          }
          if (message.message_type !== 'audio') {
            newSession.messages.push({
              id: message.id,
              type: message.message_type,
              content: message.data,
              ext: message.ext,
              date: new Date()
            })
          } else {
            newSession.messages.push({
              id: message.id,
              type: message.message_type,
              content: message.data,
              ext: message.ext,
              message_ext: message.message_ext,
              date: new Date()
            })
          }
          state.offlineMsgCount++
          state.sessions.unshift(newSession)
        }
      } catch (e) {
        console.log('RECEIVE_NEW_MESSAGE', e)
      }
    },

    RECEIVE_NOTIFICATION(state, message) {
      const notification = state.notification
      // 防重复
      if (notification.messages && notification.messages.length > 0) {
        if (typeof (notification.messages.find(item => item.id === message.id)) === 'undefined') {
          if (state.isOpenWindow === false) {
            state.noticeMsgCount = state.noticeMsgCount ? state.noticeMsgCount : 0
            notification.unReadCount = notification.unReadCount ? notification.unReadCount : 0
            notification.unReadCount++
            state.noticeMsgCount++
          }
          notification.messages.push({
            id: message.id,
            type: message.message_type,
            content: message.content,
            ext: message.ext,
            date: message.date,
            status: message.status,
            isHistory: message.isHistory
          })
        }
      } else {
        state.notification = {
          id: 1,
          user: {
            name: '通知',
            img: '../../static/IM/images/2.png'
          },
          unReadCount: 0,
          messages: []
        }
        state.notification.messages.push({
          id: message.id,
          type: message.message_type,
          content: message.content,
          ext: message.ext,
          date: message.date,
          status: message.status,
          isHistory: message.isHistory
        })
      }
    },

    // 搜索
    SET_FILTER_KEY(state, value) {
      state.filterKey = value
    },
    CLEAR_NOTICE_COUNT(state) {
      state.noticeMsgCount = 0
    },
    ADD_HISTORY_NOTICE(state, msg) {
      state.notification.message = [...state.notification.message, msg]
    },
    GET_CUSTOMER_INFO(state, payload) {
      state.customerInfo = { ...payload }
      state.customerInfo.age = parseFloat(state.customerInfo.age)
      // console.log(state.customerInfo)
    },
    GET_HOOK_USER_INFO(state, payload) {
      state.hook_info = { ...payload }
    },
    SET_HOOK(state, payload) {
      state.currentVest = payload
    },
    RELOAD_OLD_MESSAGES(state, payload) {
      if (state.currentSessionId) {
        const ind = state.sessions.findIndex(item => item.id === state.currentSessionId)
        state.sessions[ind].messages = [...payload]
      }
    },
    RELOAD_CUR_MESSAGES(state, payload) {
      const id = payload.option.user_id + '-' + payload.option.hook_user_id
      const ind = state.sessions.findIndex(item => item.id === id)
      if (ind !== -1) {
        state.sessions[ind].messages = [...payload.oldMsgs]
      }
    }
  },
  actions: {
    initData(context, user) {
      context.commit('INIT_DATA', user)
      if (context.state.currentSessionId) {
        context.dispatch('selectSession', context.state.currentSessionId)
      }
    },

    clearData({ commit, state }) {
      Cookies.remove('im_' + state.user.id)
      return new Promise((resolve, reject) => {
        commit('CLEAR_DATA')
        resolve()
      }).catch(function(reason) {
      })
    },

    // getOfflineMsgCount({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     getOfflineMessages().then(response => {
    //       commit('GET_OFFLINEMSGCOUNT', response.data[state.user.id])
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   }).catch(function(reason) {
    //   })
    // },

    ocWindow({ commit }, bool) {
      const user = window.localStorage.getItem('vuex-im-userInfo')
      commit('OC_WINDOW', bool)
      // 打开窗口同时初始数据
      if (user && bool) {
        commit('INIT_DATA', JSON.parse(user))
      }
    },

    onMsgAlert({ commit }, params) {
      commit('MSG_ALERT', params)
    },

    createSession({ commit, state }, customer) {
      customer.user_id = customer.user_id.toString()
      // console.log(state, 'createSession', customer)
      // commit('SELECT_SESSION', customer.user_id)
      const customerChange = {
        hook: {
          user_id: customer.user_id,
          user_name: customer.user_name,
          user_photo: customer.user_photo
        },
        hook_user_id: customer.user_id,
        user_id: state.user.id,
        user_name: state.user.name,
        user_photo: state.user.img
      }
      if (customerChange.user_id) {
        customerChange.user_id = customerChange.user_id.toString()
      }
      // commit('CREATE_SESSION', customer)

      commit('CREATE_SESSION', customerChange)
      commit('SELECT_SESSION', customerChange.user_id + '-' + customerChange.hook_user_id)
      // console.log(customerChange, 'createSession')
    },

    selectSession({ commit, dispatch }, id) {
      // console.log(id)
      commit('SELECT_SESSION', id)
      dispatch('getCustomerInfo', id)
    },

    // // 通过服务器发送消息
    sendMessageFromServer({ commit }, params) {
      return new Promise((resolve, reject) => {
        sendMessage(params).then(response => {
          // console.log(params, 'sendMessage------')
          commit('SEND_MESSAGE', params)
          resolve()
        }).catch(error => {
          reject(error)
        })
      }).catch(function(reason) {
      })
    },

    sendMessage({ commit }, params) {
      // console.log(params, 'sendMessage')
      commit('SEND_MESSAGE', params)
    },

    updateMessageMid({ commit }, message) {
      commit('UPDATE_MESSAGE_MID', message)
    },

    updateMessageStatus({ commit }, message) {
      // console.log(message, 'updateMessageStatus')
      commit('UPDATE_MESSAGE_STATUS', message)
    },
    // 接收消息
    receiveMessage(context, message) {
      var sessions = ''
      // 过滤自己在其他端发的消息
      // console.log('接收消息:::::', message, context)
      // if (parseInt(message.from) === parseInt(context.state.user.id)) {
      //   return
      // }
      watchSession()
      if (typeof (message.ext.hook) === 'string') {
        const hookId = JSON.parse(message.ext.hook)
        var from_id = message.ext.hook ? message.to + '-' + hookId.hook_user_id : ''
        var cur_hook_id = message.ext.hook ? hookId.hook_user_id : message.to
      } else {
        from_id = message.ext.hook ? message.to + '-' + message.ext.hook.hook_user_id : ''
        cur_hook_id = message.ext.hook ? message.ext.hook.hook_user_id : message.to
      }
      context.commit('SET_HOOK', cur_hook_id)
      // console.log(cur_hook_id, 'cur_hook_id')
      if (sessions && sessions.length > 0 && typeof (sessions.find(item => item.id === from_id)) !== 'undefined') {
        const getmessage = new Promise((resolve, reject) => {
          // var param = {}
          getHookUserInfo(cur_hook_id).then(res => {
            // param.message = message
            // param.hook = res.data
            // param.sessions=sessions

            resolve(res)
          })

          Promise.all([getmessage]).then((result) => {
          // console.log(result, '-----')
            setShow(result)

          // console.log(param, '---RECEIVE_OLD_MESSAGE---')
          })
          function setShow(result) {
            var param = {}
            // console.log(result, '----res--')
            // var param = {}
            param.message = message
            param.hook = result[0].data
            param.sessions = sessions
            context.commit('RECEIVE_OLD_MESSAGE', param)
          }
        })
      } else {
        // // 第一次接收用户信息
        // const getuserinfo = new Promise((resolve, reject) => {
        //   // var params = {}
        //   getUserInfo(message.from).then(response => {
        //     resolve(response)
        //   })
        //   // context.commit('RECEIVE_NEW_MESSAGE', params)
        //   // console.log(params, '---RECEIVE_NEW_MESSAGE---')
        // })
        const getHookUser = new Promise((resolve, reject) => {
          getHookUserInfo(cur_hook_id).then(response => {
            resolve(response)
            // params.hook = res.data
          })
        })
        Promise.all([getHookUser]).then((result) => {
          // console.log(result, '--第一次接收消息---')
          setShowRes(result)
        })

        // eslint-disable-next-line no-inner-declarations
        function setShowRes(res) {
          var params = {}
          // const data = res[0].data[0]
          params.message = message
          // console.log('第一次接收消息')
          params.customer = {
            user_id: message.from
            // user_name: data.user_name,
            // user_photo: data.user_photo
          }
          params.hook = res[0].data
          context.commit('RECEIVE_NEW_MESSAGE', params)
          // console.log(params, '---RECEIVE_NEW_MESSAGE---')
          // context.commit('RECEIVE_OLD_MESSAGE', param)
        }

        // return new Promise((resolve, reject) => {
        //   var params = {}
        //   // getUserInfo(message.from).then(response => {
        //   // const data = response.data[0]
        //   // console.log(data, 'getUserInfo')
        //   params.message = message
        //   params.customer = {
        //     user_id: message.from
        //     // user_name: data.user_name,
        //     // user_photo: data.user_photo
        //   }
        //   resolve()
        //   // }).catch(error => {
        //   //   reject(error)
        //   // })
        //   getHookUserInfo(cur_hook_id).then(res => {
        //     params.hook = res.data
        //   })
        //   context.commit('RECEIVE_NEW_MESSAGE', params)
        //   console.log(params, 'RECEIVE_NEW_MESSAGE')
        // }).catch(function(reason) {
        // })
      }
    },

    search({ commit }, value) {
      commit('SET_FILTER_KEY', value)
    },
    clearNoticeMsgCount({ commit }) {
      commit('CLEAR_NOTICE_COUNT')
    },
    onLogin(context, data) {
      // console.log(data, 'context')
      WebIM.then(res => {
        var options = {
          apiUrl: res.config.apiURL,
          user: data.user_id,
          pwd: data.im_password,
          appKey: res.config.appkey,
          success: function(res) {
            // console.log('IM登陆成功')
          },
          error: function(err) {
            console.log('err:::', err)
            setTimeout(() => {
              context.dispatch('onMsgAlert', { show: true, title: '登陆失败:请检查网络或重新登录', type: 'error' })
            }, 2000)
          }
        }
        res.conn.open(options)
        const user = {
          user_id: data.user_id,
          user_name: data.user_name,
          user_photo: data.user_photo,
          im_password: data.im_password
        }
        localStorage.setItem('vuex-im-userInfo', JSON.stringify(user))
        context.commit('INIT_DATA', user)
        // context.state.currentSessionId = context.state.customerServer.user_id + '-' + data.user_id
        context.commit('SELECT_SESSION', context.state.currentSessionId)
        // console.log(data, 'context.state.currentSessionId', context)
        // {
        // name:1,
        // img: customer.user_photo,
        // user_id: 123
        // }
        // context.commit('CREATE_SESSION', context.state.currentSessionId)
      })
    },

    onLogout(context) {
      try {
        context.dispatch('clearData')
        localStorage.setItem('vuex-im-userInfo', '')
        WebIM.then(res => {
          res.conn.close()
        })
      } catch (e) {
        console.log(e)
      }
    },

    receiveNotification(context, message) {
      let msg = {}
      msg = {
        id: message.id,
        content: message.data,
        message_type: message.message_type,
        ext: message.ext,
        date: new Date(),
        status: 'read'
      }
      msg.isHistory = false
      context.commit('RECEIVE_NOTIFICATION', msg)
    },

    getHistoryMessage: function(context, payload) {
      const options = {
        queue: payload.user_id,
        isGroup: false,
        count: payload.limit ? payload.limit : 10, // 每次获取消息条数
        success: function(msgs) {
          try {
            payload.success && payload.success(msgs)
            if (msgs.length) {
              const userInfo = JSON.parse(localStorage.getItem('userInfo'))
              const userId = userInfo && userInfo.userId
              msgs.forEach((item) => {
                const date = Number(item.time)
                let msg = {}
                const self = item.from === userId
                msg = {
                  id: item.id,
                  chatId: self ? item.to : item.from,
                  content: item.data,
                  message_type: 'txt',
                  ext: item.ext,
                  self: self,
                  date: date,
                  status: 'read'
                }
                msg.isHistory = true
                context.commit('RECEIVE_NOTIFICATION', msg)
              })
            }
          } catch (e) {
            console.log('error', e)
          }
        },
        fail: function() { }
      }
      WebIM.then(res => {
        res.conn.fetchHistoryMessages(options)
      })
    },
    addHistoryNotice({ commit }, payload) {
      commit('ADD_HISTORY_NOTICE', payload)
    },

    getCustomerInfo({ commit, state }, id) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async(resolve, reject) => {
        if (id) {
          const customer_user_id = id || state.currentSessionId
          const user_id = customer_user_id.split('-')[0]
          // console.log(user_id)
          if (customer_user_id) {
            await getCustomerInfo(user_id).then(res => {
              if (res.code === 200) {
                commit('GET_CUSTOMER_INFO', res.data)
                resolve()
              } else {
                reject()
              }
            }).catch((e) => {
              reject(e)
            })
          }
        }
      })
    },
    updateCustomerInfo(context, form) {
      return new Promise((resolve, reject) => {
        updateCustomer(form).then(response => {
          context.commit('GET_CUSTOMER_INFO', response.data)
          // MessageBox('提示', '修改客户成功')
          resolve()
        })
      })
    },
    getHookUserInfo({ commit, state }, id) {
      if (id) {
        getHookUserInfo(id).then(res => {
          if (res.code === 200) {
            // console.log(res.data, 'getHookUserInfo')
            commit('GET_HOOK_USER_INFO', res.data)
          }
        })
      }
    }
    // async getNewClientHistoricalRecord({ commit, state }, user) {
    //   const option = {
    //     user_id: user.user_id,
    //     hook_user_id: user.hook_user_id,
    //     msg_id: 0,
    //     limit: 30
    //   }
    //   getNewClientHistoricalRecord(option).then(res => {
    //     const oldMsgs = messageFilter(res.data, user.user_id)
    //     const params = {
    //       oldMsgs,
    //       option
    //     }
    //     commit('RELOAD_CUR_MESSAGES', params)
    //   })
    // }
  }
}

export default IM
